package org.example.myleet.p452;

import java.util.Arrays;
import java.util.Comparator;

public class Solution {
    public int findMinArrowShots(int[][] points) {
        if (0 == points.length) {
            return 0;
        }
        if (1 == points.length) {
            return 1;
        }
        //按point的第一位从小到大排序
        Arrays.sort(points, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0] - o2[0];
            }
        });
        int[][] intersectRanges = new int[points.length][2];
        intersectRanges[0][0] = points[0][0];
        intersectRanges[0][1] = points[0][1];
        int j = 0;
        for (int i=1; i<points.length; i++) {
            if (points[i][0] >= intersectRanges[j][0] && points[i][0] <= intersectRanges[j][1]) {
                //point与当前射箭范围有交集，求出新的交集范围
                if (points[i][0] > intersectRanges[j][0]) {
                    intersectRanges[j][0] = points[i][0];
                }
                if (points[i][1] < intersectRanges[j][1]) {
                    intersectRanges[j][1] = points[i][1];
                }
            } else {
                //如果与当前范围没有交集，则产生下一个交集范围，需要多一支箭
                ++j;
                intersectRanges[j][0] = points[i][0];
                intersectRanges[j][1] = points[i][1];
            }
        }
        //j是交集范围下标，从0开始，所以结果是+1
        return j + 1;
    }
}
